var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var ejs = require('ejs');
const session = require('express-session');
const bodyParser = require("body-parser");
var FileStore = require('session-file-store')(session);
 

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
// 设置渲染html页面
app.engine('html',ejs.__express);
app.set('view engine', 'html');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  // store: new FileStore(fileStoreOptions),
  secret: "123456", //建议使用 128 个字符的随机字符串
  name: "mysid", // 默认是sid
  cookie: {
    maxAge: 1000 * 60 * 60 *24//生存周期1小时
  },
  resave: false, //cookie之间的请求规则,假设每次登陆，true是就算会话存在也重新保存一次
  saveUninitialized: false //默认是true强制保存未初始化的会话到存储器 false不保存未初始化的会话数据，减少服务器存储的使用
})
);

app.use('/user',usersRouter)

app.get('/',(req,res)=>{
    res.redirect('/index')
})
app.use('/index',indexRouter)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
